package dao;

import util.JDBCUtil;
import model.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
    *
    * User表的处理(增删改)--逻辑处理
    */
public class UserDao {
    private JDBCUtil jdbcUtil;
    /**
     *查询用户信息
     */
    public UserDao() {
        jdbcUtil = new JDBCUtil();
    }

//  根据用户名、密码查询
    public User finduser(String username , String password){
        try {
            JDBCUtil jdbcUtil = new JDBCUtil();
            String sql = "SELECT * FROM user where username=? and password=?"; // 假设数据库表名为 users
            ResultSet resultSet = jdbcUtil.prepareQuery(sql,username,password);
            User user=new User();
            if (resultSet.next()) {
                user.setUsername(resultSet.getString("username")) ;
                user.setGender(resultSet.getString("gender"));
                user.setProfession(resultSet.getString("profession"));
                user.setDescription(resultSet.getString("description"));
                return user;
            }
        }
      catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
      }

//管理员登录
    public User manager(String username , String password) {
        try {
            JDBCUtil jdbcUtil = new JDBCUtil();
            String sql = "SELECT * FROM user where role=2 and username=? and password=?"; // 假设数据库表名为 users
            ResultSet resultSet = jdbcUtil.prepareQuery(sql,username,password);
            User user=new User();
            if (resultSet.next()) {
                user.setUsername(resultSet.getString("username")) ;
                user.setGender(resultSet.getString("gender"));
                user.setProfession(resultSet.getString("profession"));
                user.setDescription(resultSet.getString("description"));
                return user;
            }
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


//  根据用户名进行查询
    private User search(String searchUsername) {
        List<Map<String, Object>> userList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();

        try {
            String sql = "SELECT * FROM 02_38_yangyang WHERE username = ?";
            ResultSet resultSet = jdbcUtil.prepareQuery(sql, searchUsername);

            while (resultSet.next()) {
                int id = resultSet.getInt("user_id");
                String gender = resultSet.getString("gender");
                String profession = resultSet.getString("profession");
                String favor = resultSet.getString("favor");
                String description = resultSet.getString("description");
                int state = resultSet.getInt("state");
                int role = resultSet.getInt("role");

                // 检查是否存在 null 值，避免空指针异常
                if (gender != null && profession != null && favor != null && description != null) {
                    Map<String, Object> user = Map.of(
                            "id", id,
                            "username", searchUsername,
                            "gender", gender,
                            "profession", profession,
                            "favor", favor,
                            "description", description,
                            "state", state,
                            "role", role
                    );


                    // 将用户信息Map添加到列表中
                    userList.add(user);
                }
                User user=new User();
                if (resultSet.next()) {
                    user.setUsername(resultSet.getString("username")) ;
                    user.setGender(resultSet.getString("gender"));
                    user.setProfession(resultSet.getString("profession"));
                    user.setDescription(resultSet.getString("description"));
                    return user;
                }
            }
            // 处理数据库异常
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtil.closeConnection(); // 关闭数据库连接
        }

       return null;
    }

//    根据id查找，并删除
private boolean delete( int userId){
    JDBCUtil jdbcUtil = new JDBCUtil();

    try {
        String sql = "DELETE FROM `02_38_yangyang` WHERE user_id = ?";
        PreparedStatement pstmt = jdbcUtil.prepareStatement(sql);
        pstmt.setInt(1, userId);
        int rowsAffected = pstmt.executeUpdate();
        return rowsAffected > 0; // 如果影响的行数大于0，表示删除成功
    }catch (SQLException e) {
        throw new RuntimeException(e);
    }
    // 处理数据库异常
    finally {
        jdbcUtil.closeConnection(); // 关闭数据库连接
    }
}


    public boolean checkPassword(String username, String oldPassword) {
        String sql = "SELECT * FROM 02_38_yangyang WHERE username = ? AND password = ?";
        try (ResultSet resultSet = jdbcUtil.prepareQuery(sql, username, oldPassword)) {
            return resultSet.next(); // 如果查询结果存在记录，则返回 true，否则返回 false
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 发生异常时返回 false
        }
    }

    public boolean updatePassword(String username, String newPassword) {
        String sql = "UPDATE 02_38_yangyang SET password = ? WHERE username = ?";
        return jdbcUtil.update(sql, newPassword, username); // 返回更新结果
    }


    private List<User> allSearch() {
        List<User> userList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();

        try {
            String sql = "SELECT * FROM 02_38_yangyang"; // Select all data
            ResultSet resultSet = jdbcUtil.query(sql); // No need for parameters

            while (resultSet.next()) {
                User user = new User(); // Create a new User object for each row
                user.setId(resultSet.getInt("user_id"));
                user.setUsername(resultSet.getString("username"));
                user.setGender(resultSet.getString("gender"));
                user.setProfession(resultSet.getString("profession"));
                user.setFavorString(resultSet.getString("favor"));
                user.setDescription(resultSet.getString("description"));
                user.setState(resultSet.getInt("state"));
                user.setRole(resultSet.getInt("role"));

                // Add the User object to the list
                userList.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtil.closeConnection(); // Close database connection
        }

        return userList;
    }
    public User getUserById(int userId) {
        String sql = "SELECT * FROM 02_38_yangyang WHERE user_id = ?";
        try {
            ResultSet resultSet = jdbcUtil.prepareQuery(sql, userId);
            if (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt("user_id"));
                user.setUsername(resultSet.getString("username"));
                user.setGender(resultSet.getString("gender"));
                user.setProfession(resultSet.getString("profession"));
                user.setFavorString(resultSet.getString("favor"));
                user.setDescription(resultSet.getString("description"));
                user.setState(resultSet.getInt("state"));
                user.setRole(resultSet.getInt("role"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtil.closeConnection();
        }
        return null;
    }

    public boolean updateUser(User user) {
        String sql = "UPDATE 02_38_yangyang SET username = ?, gender = ?, profession = ?, favor = ?, description = ?, state = ?, role = ? WHERE user_id = ?";
        return jdbcUtil.update(sql, user.getUsername(), user.getGender(), user.getProfession(), user.getFavorString(), user.getDescription(), user.getState(), user.getRole(), user.getId());
    }

}
